package com.microsoft.socialphoto.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import android.graphics.drawable.Drawable;

import com.microsoft.socialphoto.Config;

public class Utils {
	Drawable getDrawableFromUrl(String url, String src_name)
			throws java.net.MalformedURLException, java.io.IOException {
		return Drawable.createFromStream(
				((java.io.InputStream) new java.net.URL(url).getContent()),
				src_name);
	}

	public static void CopyStream(InputStream is, OutputStream os) {
		final int buffer_size = 1024;
		try {
			byte[] bytes = new byte[buffer_size];
			for (;;) {
				int count = is.read(bytes, 0, buffer_size);
				if (count == -1)
					break;
				os.write(bytes, 0, count);
			}
		} catch (Exception ex) {
		}
	}

	public static String getThumbnailUrlFromFileName(String fileName) {
		return Config.THUMBNAIL_SRC + fileName;
	}

	public static String getImageUrlFromFileName(String fileName) {
		return Config.IMAGE_SRC + fileName;
	}

	public static HttpResponse sendPostData(String url,
			ArrayList<NameValuePair> postData) {
		// Create a new HttpClient and Post Header
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(url);

		try {
			httppost.setEntity(new UrlEncodedFormEntity(postData));

			// Execute HTTP Post Request
			return httpclient.execute(httppost);

		} catch (ClientProtocolException e) {
		} catch (IOException e) {
		}

		return null;
	}

	public static String getContentFromInputStream(InputStream inputStream) {
		StringBuffer data = new StringBuffer();
		InputStreamReader isr = new InputStreamReader(inputStream);

		BufferedReader in = new BufferedReader(isr);

		String inputLine;

		try {
			while ((inputLine = in.readLine()) != null) {
				data.append(inputLine);
			}

			in.close();
			isr.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return data.toString();
	}
}
